
package org.apache.solr.search;

import java.io.IOException;
import org.apache.lucene.index.AtomicReaderContext;
import org.apache.lucene.search.Collector;
import org.apache.lucene.search.Scorer;


/** A simple delegating collector where one can set the delegate after creation */
public class DelegatingCollector extends Collector {

    /* for internal testing purposes only to determine the number of times a delegating collector chain was used */
    public static int setLastDelegateCount;
    protected Collector delegate;
    protected Scorer scorer;
    protected AtomicReaderContext context;
    protected int docBase;

    public Collector getDelegate() {
        return delegate;
    }

    public void setDelegate(Collector delegate) {
        this.delegate = delegate;
    }

    /**
     * Sets the last delegate in a chain of DelegatingCollectors
     */
    public void setLastDelegate(Collector delegate) {
        DelegatingCollector ptr = this;
        for (; ptr.getDelegate() instanceof DelegatingCollector; ptr = (DelegatingCollector) ptr.getDelegate());
        ptr.setDelegate(delegate);
        setLastDelegateCount++;
    }

    @Override
    public void setScorer(Scorer scorer) throws IOException {
        this.scorer = scorer;
        delegate.setScorer(scorer);
    }

    @Override
    public void collect(int doc) throws IOException {
        delegate.collect(doc);
    }

    @Override
    public void setNextReader(AtomicReaderContext context) throws IOException {
        this.context = context;
        this.docBase = context.docBase;
        delegate.setNextReader(context);
    }

    @Override
    public boolean acceptsDocsOutOfOrder() {
        return delegate.acceptsDocsOutOfOrder();
    }
}
